package com.boilermaker.lotterysystem.common.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@EnableRabbit
public class LotteryRabbitMQConfig {

    public static final String LOTTERY_QUEUE = "lottery.record.queue";
    public static final String LOTTERY_EXCHANGE = "lottery.record.exchange";
    public static final String LOTTERY_ROUTING_KEY = "lottery.record.routing";

    public static final String LOTTERY_DLX_QUEUE = "lottery.record.dlx.queue";
    public static final String LOTTERY_DLX_EXCHANGE = "lottery.record.dlx.exchange";
    public static final String LOTTERY_DLX_ROUTING_KEY = "lottery.record.dlx.routing";

    /**
     * 业务队列
     */
    @Bean
    public Queue lotteryRecordQueue() {
        return QueueBuilder.durable(LOTTERY_QUEUE)
                .deadLetterExchange(LOTTERY_DLX_EXCHANGE)    // 绑定死信交换机
                .deadLetterRoutingKey(LOTTERY_DLX_ROUTING_KEY) // 死信路由键
                .ttl(60000) // TTL 60秒，防止消息无限期堆积
                .maxLength(10000) // 队列最大长度，防止内存溢出
                .build();
    }

    /**
     * 业务交换机
     */
    @Bean
    public DirectExchange lotteryRecordExchange() {
        return new DirectExchange(LOTTERY_EXCHANGE, true, false);
    }

    /**
     * 业务队列与交换机绑定
     */
    @Bean
    public Binding bindingLotteryRecord() {
        return BindingBuilder.bind(lotteryRecordQueue())
                .to(lotteryRecordExchange())
                .with(LOTTERY_ROUTING_KEY);
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue lotteryRecordDlxQueue() {
        return QueueBuilder.durable(LOTTERY_DLX_QUEUE)
                .ttl(86400000) // 死信消息保留24小时
                .maxLength(5000) // 死信队列容量限制
                .build();
    }

    /**
     * 死信交换机
     */
    @Bean
    public DirectExchange lotteryRecordDlxExchange() {
        return new DirectExchange(LOTTERY_DLX_EXCHANGE, true, false);
    }

    /**
     * 死信队列与交换机绑定
     */
    @Bean
    public Binding bindingLotteryRecordDlx() {
        return BindingBuilder.bind(lotteryRecordDlxQueue())
                .to(lotteryRecordDlxExchange())
                .with(LOTTERY_DLX_ROUTING_KEY);
    }

    /**
     * 消息转换器统一使用 JSON 格式
     */
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 自定义RabbitTemplate，配置重试机制
     */
//    @Bean
//    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
//        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
//        rabbitTemplate.setMessageConverter(jsonMessageConverter());
//
//        // 设置消息确认回调
//        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
//            if (!ack) {
//                // 记录消息发送失败日志，便于后续排查
//                System.getLogger("LotteryRabbitMQ").log(System.Logger.Level.ERROR,
//                        "消息发送失败: " + cause);
//            }
//        });
//
//        // 设置消息返回回调（当消息无法路由到队列时）
//        rabbitTemplate.setReturnsCallback(returned -> {
//            System.getLogger("LotteryRabbitMQ").log(System.Logger.Level.WARN,
//                    "消息无法路由到队列: " + returned.getMessage() + ", 路由键: " + returned.getRoutingKey());
//        });
//
//        return rabbitTemplate;
//    }
}
